const fs = require('fs')
const path = require('path')
const multiparty = require('multiparty');
const execSync = require('child_process').execSync
const UPLOADPATH = path.join(process.cwd(), 'public', 'files')

function mkdirsSync(dirPath) {
	if (!fs.existsSync(dirPath)) {
		let pathTmp = ''
		let dirPathArr = dirPath.split(path.sep)
		for (let i = 0; i < dirPathArr.length; i++) {
			let dirname = dirPathArr[i]
			if (!dirname)
				dirname = path.sep;
			if (pathTmp) {
				pathTmp = path.join(pathTmp, dirname);
			} else {
				pathTmp = dirname;
			}
			if (!fs.existsSync(pathTmp)) {
				fs.mkdirSync(pathTmp)
			}
		}
	}
	return true;
}

module.exports = {

	mkdirsSync,

	mvFileUrl,

	removeFile(url) {
		let removePath = path.join(UPLOADPATH, url.replace(/^\/files/, ''))
		console.log('removePath', removePath)
		fs.unlinkSync(removePath)
	},

	uploadFiles(req, options = {}) {
		let {
			destDir,
			fileName = '',
			originalFilename = false,
			base64 = false,
		} = options
		let form = new multiparty.Form();
		return new Promise((resolve, reject) => {
			form.parse(req, function(err, fields, files) {
				console.log('err', err)
				if (err) {
					return resolve({
						err,
					});
				}
				console.log('files', files)
				console.log('fields', fields)
				let attachment = parseFile(files);
				console.log('attachment', attachment)
				if (!attachment || !attachment.path || !attachment.originalFilename)
					return resolve({
						err: '上传失败！',
					});
				let url = ''
				console.log('attachment.originalFilename', attachment.originalFilename)
				if (fileName)
					fileName = `${fileName}.${attachment.originalFilename.replace(/\S*\./, '')}`
				else if (originalFilename)
					fileName = attachment.originalFilename
				else
					fileName = attachment.path.replace('/tmp/', '')
				if (base64) {
					url = toBase64(attachment.path)
				} else if (destDir) {
					url = mvFileUrl(attachment.path, destDir, fileName)
				}
				return resolve({
					attachment,
					fields,
					files,
					fileName,
					url,
				});
			});
		})
	},
}

function parseFile(files) {
	let file = files['upload']
	if (file && file[0])
		return file[0]
	for (let f in files)
		if (files[f] && files[f][0])
			return files[f][0]
	return null
}

/**
 * 移动文件，返回文件访问url
 * @param  {[type]} attachment [description]
 * @param  {[type]} destDir    [description]
 * @return {[type]}            [description]
 */
function mvFileUrl(source, destDir = '', fileName) {
	let absoluteDestDir = path.join(UPLOADPATH, destDir)
	mkdirsSync(absoluteDestDir)
	let destFilePath = path.join(absoluteDestDir, fileName);
	// 将文件从临时系统目录转移到指定目录
	try {
		execSync(`mv ${source} ${destFilePath}`)
	} catch (e) {
		console.log(e)
		let readable = fs.createReadStream(source);
		let writable = fs.createWriteStream(destFilePath);
		readable.pipe(writable);
		fs.unlinkSync(source)
	}
	return path.join('/files', destDir, fileName)
}

/**
 * 转成base64
 * @param  {[type]} path [description]
 * @return {[type]}      [description]
 */
function toBase64(path) {
	let buff = fs.readFileSync(path)
	return `data:image/jpg;base64,${buff.toString('base64')}`
}